﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyDDD.Application
{
    public class BusinessExceptionFilter : ExceptionFilterAttribute
    {

        private class BusinessError
        {
            //public object Exception { get; set; } = default!;


            public int Code { get; set; } = default!;
            public string Title { get; set; } = default!;
            public string Message { get; set; } = default!;
            public Collection<object> Errors { get; set; } = new();
        }

        public override void OnException(ExceptionContext context)
        {
            if (context.Exception == null)
            {
                return;
            }

            if (context.Exception is BusinessException)
            {
                context.ExceptionHandled = true;
                var ex = (BusinessException)context.Exception;
                var error = new BusinessError()
                {
                    Code = ex.Code,
                    Title = ex.Title,
                    Message = ex.Message,
                    //Errors = ex.Errors,
                    //Exception = context.Exception,
                };
                context.Result = new ObjectResult(error) { StatusCode = 500 };
            }
        }
    }
}
